<template>
  <a-card size="small" style="margin-bottom: 10px" :bordered="false">
    <a-flex justify="space-between">
      <a-button type="primary" ghost @click="addRule">新增解析规则</a-button>
      <a-button type="primary" ghost @click="saveRule" :loading="saveLoading" :disabled="saveLoading">保存规则
      </a-button>
    </a-flex>
  </a-card>
  <a-card size="small" style="margin-bottom: 10px" :bordered="false">
    <a-radio-group v-model:value="tab" @change="tabChange">
      <a-radio-button value="keep">保持寄存器-[03]</a-radio-button>
      <a-radio-button value="input">输入寄存器-[04]</a-radio-button>
    </a-radio-group>
  </a-card>
  <a-table :loading="loading" :columns="columns" :dataSource="data?data.filter(x=>x.registerType==tab):[]"
           :pagination="false" :scroll="{y:yScroll ,x:1920}"
           :rowClassName="setRowClassName">
    <template #bodyCell="{ column, text, record }">
      <template v-if="column.dataIndex === 'addName'">
        <a-input v-model:value="record.addName"></a-input>
      </template>
      <template v-if="column.dataIndex === 'address'">
        <a-input v-model:value="record.address"></a-input>
      </template>
      <template v-if="column.dataIndex === 'addOffset'">
        <a-input v-model:value="record.addOffset"></a-input>
      </template>
      <template v-if="column.dataIndex === 'dataType'">
        <a-input v-model:value="record.dataType"></a-input>
      </template>
      <template v-if="column.dataIndex === 'm'">
        <a-input v-model:value="record.m"></a-input>
      </template>
      <template v-if="column.dataIndex === 'unit'">
        <a-input v-model:value="record.unit"></a-input>
      </template>
      <template v-if="column.dataIndex === 'forwardMode'">
        <a-select style="width: 100%" v-model:value="record.forwardMode" :options="modeList"></a-select>
      </template>
      <template v-if="column.dataIndex === 'forwardType'">
        <a-select style="width: 100%" v-model:value="record.forwardType" :options="typeList"></a-select>
      </template>
      <template v-if="column.dataIndex === 'config104'">
        <a-input v-if="record.forwardMode=='direct'" v-model:value="record.address104"></a-input>
        <a-button v-else-if="record.forwardMode=='split'" type="link" @click="addressInfoEdit(record)">配置</a-button>
        <a-space v-else>不可配置</a-space>
      </template>
      <template v-if="column.dataIndex === 'ruleContext'">
        <a-flex :style="record.ruleContext?`background-color: ${`#a4d9a4`}`:''" justify="center">
          <a-button type="link" @click="ruleEdit(record)">编辑</a-button>
        </a-flex>

      </template>
      <template v-if="column.dataIndex === 'action'">
        <a-button danger type="link" @click="deleteRule(record)">清除规则</a-button>
        <a-button danger type="link" @click="deleteRecord(record)">删除</a-button>
      </template>
    </template>
  </a-table>
  <a-modal v-model:open="open" width="500px" @ok="editOk" @cancel="editCancel" ok-text="确定" cancel-text="取消">
    <a-form style="margin-top: 30px">
      <a-form-item label="当采集值">
        <a-flex justify="space-between">
          <a-select style="width: 38%" v-model:value="editRule.condition" allow-clear
                    :options="[{label:'大于',value:'>'},{label:'小于',value:'<'},{label:'相等',value:'='}]"></a-select>
          <a-input style="width: 60%" v-model:value="editRule.conditionValue"></a-input>
        </a-flex>
      </a-form-item>
      <a-form-item label="则采集值">
        <a-flex justify="space-between">
          <a-select style="width: 38%" v-model:value="editRule.change" allow-clear
                    :options="[{label:'增加',value:'+'},{label:'减少',value:'-'},{label:'设置为',value:'='}]"></a-select>
          <a-input style="width: 60%" v-model:value="editRule.changeValue"></a-input>
        </a-flex>
      </a-form-item>
    </a-form>
  </a-modal>
  <a-modal v-model:open="open104" width="900px" @ok="edit104Ok" @cancel="editCancel" ok-text="确定" cancel-text="取消">
    <a-flex >
      <a-button type="primary" ghost @click="createEditAddressInfo" style="margin-top: 20px">增加</a-button>
    </a-flex>
    <a-table :columns="columns104" :data-source="editAddressInfo" :pagination="false" :scroll="{y:500}">
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.dataIndex === 'name'">
          <a-input v-model:value="record.name"></a-input>
        </template>
        <template v-if="column.dataIndex === 'address'">
          <a-input v-model:value="record.address"></a-input>
        </template>
        <template v-if="column.dataIndex === 'tv'">
          <a-input v-model:value="record.tv"></a-input>
        </template>
        <template v-if="column.dataIndex === 'action'">
          <a-button danger type="link" @click="deleteAddressInfoRecord(record)">删除</a-button>
        </template>
      </template>
    </a-table>

  </a-modal>
</template>
<script setup>
import {ref} from "vue";
import {message} from "ant-design-vue";
import {uuid} from "@/utils/common.js";
import {baseRequest} from "@/utils/request.js";
import Index from "@/view/index.vue";

const tab = ref('keep')
const open104 = ref(false)
const open = ref(false)
const loading = ref(false)
const saveLoading = ref(false)
const yScroll = `calc(100vh - ${330}px)`
const data = ref([])
const editRecord = ref({})
const editAddressInfo = ref([])
const editRule = ref({})

const modeList = ref([
  {
    label: "直接转发",
    value: "direct",
  },
  {
    label: "分解转发",
    value: "split",
  }
])
const typeList = ref([
  {
    label: "模拟量",
    value: "analog",
  },
  {
    label: "开关量",
    value: "switch",
  }
])
const columns = [
  {
    title: '测点名称',
    dataIndex: 'addName',
    width: 200,
  },
  {
    title: '寄存器地址',
    dataIndex: 'address',
    width: 200,
  },
  {
    title: '地址偏移量',
    dataIndex: 'addOffset',
  },
  {
    title: '数据类型',
    dataIndex: 'dataType',
  },
  {
    title: '倍率',
    dataIndex: 'm',
  },
  {
    title: '单位',
    dataIndex: 'unit',
  },
  {
    title: '转发模式',
    dataIndex: 'forwardMode',
  },
  {
    title: '转发104量类型',
    dataIndex: 'forwardType',
  },
  {
    title: '104转发寄存器配置',
    dataIndex: 'config104',
  },
  {
    title: '转发修正',
    dataIndex: 'ruleContext',
    width: 120,
    fixed: 'right'
  },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    width: 180,
    fixed: 'right'
  }
]
const columns104 = [
  {
    title: '名称',
    dataIndex: 'name',
  },
  {
    title: '104地址',
    dataIndex: 'address',
  },
  {
    title: '默认值',
    dataIndex: 'def',
  },
  {
    title: '激活值',
    dataIndex: 'tv',
  },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
  }
]
const tabChange = (e) => {
  console.log(tab.value)
}

const setRowClassName = (record, index) => {
  if (record.id.indexOf("new") != -1) {
    return 'rowNew'
  } else {
    return 'row'
  }
}
const loadData = () => {
  loading.value = true
  baseRequest("/rule/all", {}).then(res => {
    data.value = res.data.data
  }).catch(() => {

  }).finally(() => {
    loading.value = false
  })
}
loadData()
const addRule = () => {
  data.value = [{
    id: 'new' + uuid(8, 16),
    addName: '测点-' + (data.value.length + 1),
    address: '0',
    addOffset: '1',
    dataType: 'U16',
    m: 1,
    unit: null,
    address104: null,
    ruleContext: null,
    registerType: tab.value
  }, ...data.value]
}
const deleteRecord = (record) => {
  data.value = data.value.filter(item => item.id !== record.id)
}
const deleteAddressInfoRecord = (record) => {
  editAddressInfo.value = editAddressInfo.value.filter(item => item.id !== record.id)
}
const deleteRule = (record) => {
  data.value.forEach(item => {
    if (item.id == record.id) {
      item.ruleContext = null
    }
  })
}
const ruleEdit = (record) => {
  editRecord.value = record
  if (record.ruleContext) {
    editRule.value = JSON.parse(record.ruleContext)
  }
  open.value = true
}

const addressInfoEdit = (record) => {
  editRecord.value = record
  if (record.addressInfo104) {
    editAddressInfo.value = JSON.parse(record.addressInfo104)
  }
  open104.value = true
}
const editCancel = () => {
  editRule.value = {}
  editAddressInfo.value = []
  editRecord.value = {}
  open.value = false
  open104.value = false
}
const editOk = () => {
  editRecord.value.ruleContext = JSON.stringify(editRule.value)
  data.value.forEach((item, index) => {
    if (item.id == editRecord.value.id) {
      item.ruleContext = editRecord.value.ruleContext
    }
  })
  editCancel()
}
const edit104Ok = () => {
  editRecord.value.addressInfo104 = JSON.stringify(editAddressInfo.value)
  data.value.forEach((item, index) => {
    if (item.id == editRecord.value.id) {
      item.addressInfo104 = editRecord.value.addressInfo104
    }
  })
  editCancel()
}

const createEditAddressInfo = () => {
  editAddressInfo.value.push(
      {
        id: uuid(8, 16),
        name: null,
        address: null,
        tv: null,
        def: 'false',
      }
  )
}


const saveRule = () => {
  saveLoading.value = true
  baseRequest("/rule/save/all", data.value, 'post').then(res => {
    if (res.data.code == 200) {
      loadData()
      message.success("保存成功，重启服务后生效")
    }
  }).catch(() => {
  }).finally(() => {
    saveLoading.value = false
  })
}
</script>
<style scoped>
/deep/ .row {
  background-color: #e6e7f9 !important;
}

/deep/ .rowNew {
  background-color: #b0b0b1 !important;
}
</style>
